package com.dnjn.happiness.emo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.emo.domain.Risk;
import com.dnjn.happiness.emo.domain.vo.RecordScore;
import com.dnjn.happiness.emo.mapper.RiskMapper;
import com.dnjn.happiness.emo.service.IRiskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 风控 服务实现类
 * </p>
 *
 * @author Amber
 * @since 2023-10-09
 */
@Slf4j
@Service
public class RiskServiceImpl extends ServiceImpl<RiskMapper, Risk> implements IRiskService {

    @Override
    public List<RecordScore> loadInfo(Long userId) {

        List<Risk> list = lambdaQuery().eq(Risk::getDeleted, "0").list();
        Map<String, BigDecimal> map = list.stream().collect(Collectors.toMap(Risk::getRtype, Risk::getWeight));

        List<RecordScore> res = list.stream()
//                .filter(el -> !HvRiskType.valueOf(el.getRtype()).isCustom())
                .filter(el -> StringUtils.isNotBlank(el.getTableName())) //?
                .parallel()
                .map(risk -> {
                    log.info("{} {}", risk.getRtype(), risk.getWeight());
                    RecordScore score = baseMapper.selectRecordX(userId, risk.getTableName());
                    if (Objects.nonNull(score)) {
                        score.resetRisk(risk).resetTotal();
                    } else {
                        score = RecordScore.create(userId, risk);
                        //todo
                    }
                    return score;
                }).collect(Collectors.toList());

        return res;
    }

    @Override
    public Risk getByRiskType(String rtype) {
        return lambdaQuery().eq(Risk::getDeleted, "0").eq(Risk::getRtype, rtype).one();
    }
}
